// pages/MQTTWXDemo/MQTTWXDemo.js

import mqtt from '../../utils/mqtt.min.js';

var  clinetConn = null;

var app = getApp()

Page({

  getConnectInfo:function(e){
    console.log(e.detail.value.InputSeverIP);
    console.log(e.detail.value.InputSeverPort);
    console.log(e.detail.value.InputSeverUser);
    console.log(e.detail.value.InputSeverPass);
  },

  InputSeverIP:function(e){
    this.setData({
      InputSeverIP:e.detail.value
    })
  },
  InputSeverPort:function(e){
    this.setData({
      InputSeverPort:e.detail.value
    })
  },
  InputSeverUser:function(e){
    this.setData({
      InputSeverUser:e.detail.value
    })
  },

  InputSeverPass:function(e){
    this.setData({
      InputSeverPass:e.detail.value
    })
  },

  /**
   * 页面的初始数据
   */
  data: {
    InputSeverIP: '192.168.218.131',
    InputSeverPort: '8083',
    InputSeverUser: 'admin',
    InputSeverPass: 'public'
  },

  connectionServer: function () {

    const options = {
      clean: true, // 保留回话
      connectTimeout: 4000, // 超时时间
      clientId: 'WX_MQTT_Client', // 认证信息
      port: this.data.InputSeverPort,
      username:  this.data.InputSeverUser,
      password:  this.data.InputSeverPass
    }

    const connectUrl = 'wx://'+this.data.InputSeverIP+'/mqtt';
    // js的全局公用变量保存在App.js文件中

    clinetConn = new mqtt.connect(connectUrl, options)  
 
    app.setAppdata(clinetConn)

    clinetConn.on('reconnect', (error) => {
      console.log('正在重连:', error)
    })

    clinetConn.on('error', (error) => {
      console.log('连接失败:', error)
    })
    
    clinetConn.on('message', (topic, message) => {
      console.log('收到消息：', topic, message.toString())
    })
  },

  ConServer: function (e) {
    this.connectionServer();
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})

